package com.android.car.screensaver;

import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class CrashHandler implements UncaughtExceptionHandler {

    private static final String TAG = "CrashHandler";
    // 系统默认的UncaughtException处理类
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    // CrashHandler实例
    private static CrashHandler instance;
    // 程序的Context对象
    private Context mContext;

    private CrashHandler() {
    }

   
    public static CrashHandler getInstance() {
        if (instance == null)
            instance = new CrashHandler();
        return instance;
    }

   
    public void init(Context context) {
        mContext = context;
        Log.e(TAG, "init");
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

   
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            // 退出程序
            Log.e(TAG, "error: " + (ex == null ? "null" : ex.getMessage()));
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

   
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        if (mContext != null) {
            mContext.sendBroadcast(new Intent("rk.android.show.navi"));
            Log.e(TAG, "handleException send broadcast");
        }
        return true;
    }

}
